package com.ruoyi.dwzzzy.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.dwzzzy.domain.SourceFile;
import com.ruoyi.dwzzzy.service.SourceFileService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysUser;
import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description :
 * @auther :   zhanvie
 * @Date :   2021-03-22
 */
@Controller
@RequestMapping("/business/file")
public class FileProcessController extends BaseController {

    private static final String midDir = "resource/";

    @Resource
    private SourceFileService sfs;

    @Transactional(rollbackFor = Exception.class)
//    @RequiresPermissions("business:file:upload")
    @Log(title = "资质资源上传", businessType = BusinessType.UPLOAD)
    @PostMapping("/{type}/zy/{zyid}")
    @ResponseBody
    public AjaxResult add(@PathVariable Long zyid, @PathVariable String type, @RequestParam("files") List<MultipartFile> files) throws IOException {
        List<Long> result = new ArrayList<>();
        String profile = Global.getProfile();
        String uploadDirBasePath = FilenameUtils.concat(profile, midDir + type);
        String year = String.valueOf(LocalDateTime.now().getYear());
        String uploadDirPath = FilenameUtils.concat(uploadDirBasePath, year);
        File dir = new File(uploadDirPath);
        if(!dir.exists()) {
            dir.mkdirs();
        }

        SysUser user = ShiroUtils.getSysUser();
        Date nowDate = DateUtils.getNowDate();
        for (MultipartFile file : files) {
            String uuidBaseName = UUID.randomUUID().toString();
            String originalFilename = file.getOriginalFilename();
            String fileNewName = uuidBaseName + "." + FilenameUtils.getExtension(originalFilename);
            String newFilePath = FilenameUtils.concat(uploadDirPath, fileNewName);
            File targetFile = new File(newFilePath);
            file.transferTo(targetFile);

            SourceFile sourceFile = new SourceFile();
            sourceFile.setZyid(zyid);
            sourceFile.setOriginalName(originalFilename);
            sourceFile.setRealPath(newFilePath);
            sourceFile.setCreateBy(user.getUserName());
            sourceFile.setCreateTime(nowDate);
            sfs.save(sourceFile);
            result.add(sourceFile.getFid());
        }
        return AjaxResult.success(result);
    }

    @GetMapping("/zy/{zyid}")
    @ResponseBody
    public AjaxResult getSourceFileList(@PathVariable Long zyid) {
        SourceFile s = new SourceFile();
        s.setZyid(zyid);
        return AjaxResult.success(sfs.getSourceFiles(s));
    }

    @GetMapping("/{fid}")
    public void downloadPdf(@PathVariable Long fid, HttpServletResponse response) throws IOException {
        SourceFile fileByid = sfs.getFileByid(fid);
        String realPath = fileByid.getRealPath();
        File file = new File(realPath);
        OutputStream os = response.getOutputStream();
        IOUtils.copy(new FileInputStream(file), os);
    }

}
